home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2294 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.0 KB  |  61 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: pstaite@vnet.ibm.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Using a Base constructor for a derived class
  5. Date: 16 Jan 1996 20:10:16 GMT
  6. Organization: IBM OS/2 Device Driver Development  Rochester, MN
  7. Message-ID: <4dh0n8$19kh@locutus.rchland.ibm.com>
  8. References: <4ddui9$a14@felix.cc.gatech.edu>
  9. Reply-To: pstaite@vnet.ibm.com
  10. NNTP-Posting-Host: warpone.rchland.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4ddui9$a14@felix.cc.gatech.edu>, culbreth@cc.gatech.edu (Matthew W. Culbreth) writes:
  14. >Howdy,
  15. >
  16. >I have a base class with a constructor.  This class is never used
  17. >in my application.  I have three classes derived from this class.
  18. >
  19. >When I create an instant of one of the derived class, I want to use the 
  20. >constructor from the base class.  The compiler is stating that it can't find 
  21. >the constructor for the arguments passed for any of the derived classes.
  22. >Are constructors inherited the same as member functions?
  23.  
  24. No.  For example:
  25.  
  26. class foo {
  27.   public:
  28.     foo( int );
  29. };
  30.  
  31. class bar : public foo {
  32. };
  33.  
  34. Note, class bar has no constructor that takes an int, it has only the 
  35. compiler-generated default constructor.  However, even this won't 
  36. compile :-(
  37.  
  38. By default, all derived class constructors call the base class' default 
  39. constructor. (ie. the parameterless one)  However, class foo has no 
  40. parameterless constructor.  What you really need is:
  41.  
  42. class bar : public foo {
  43.   public:
  44.     bar( int x ) : foo( x ) {}
  45. };
  46.  
  47. This declares (and defines inline) an int constructor for bar.  It also 
  48. explicitly directs the compiler to use the int constructor for the base 
  49. class (foo) part of the derived class (bar).
  50.  
  51. So, you're derived classes will need to declare/define all "types" of 
  52. constructors you want them to make available.  In addition, if you want 
  53. to use something other than the base class' default constructor, you'll 
  54. have to have each derived constructor specify it in the 
  55. constructor-initializer list.
  56.  
  57.  
  58. Phil Staite, team OS/2
  59. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  60.  
  61.